﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Diagnostics;

namespace ApiServer.Filters
{
    /// <summary>
    /// 行为过滤器
    /// </summary>
    public class ActionFilter:IAsyncActionFilter
    {
        private readonly ILogger<ActionFilter> _logger;
        public ActionFilter(ILogger<ActionFilter> logger)
        {
            _logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //throw new NotImplementedException();
            //StopWatch 这个类是一个秒表，可以统计所用的时间
            Stopwatch sw = new Stopwatch();
            sw.Start();//开始计时

            //要做的事情
            await next();

            //停止计时
            sw.Stop();

            long n=sw.ElapsedMilliseconds;//所用时间（毫秒）

            //还可以记录其他信息
            //略
            //

            //记录nlog日志
            _logger.LogInformation("运行了：" + n.ToString() + "毫秒");

            //var log = NLog.LogManager.GetCurrentClassLogger();
            //log.Info("运行了：" + n.ToString() + "毫秒");



        }
    }
}
